package com.easylinkin.linkappapi.knowledgebase.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.knowledgebase.entity.KnowledgeBase;
import com.easylinkin.linkappapi.knowledgebase.entity.KnowledgeType;
import com.easylinkin.linkappapi.knowledgebase.mapper.KnowledgeBaseMapper;
import com.easylinkin.linkappapi.knowledgebase.mapper.KnowledgeTypeMapper;
import com.easylinkin.linkappapi.knowledgebase.service.KnowledgeTypeService;
import com.easylinkin.linkappapi.knowledgebase.util.Node;
import com.easylinkin.linkappapi.knowledgebase.util.NodeUtil;
import com.easylinkin.linkappapi.knowledgebase.vo.KnowledgeTypeVO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 知识类别表 服务实现类
 * </p>
 *
 * @author xy
 * @since 2021-12-02
 */
@Service
public class KnowledgeTypeServiceImpl extends
    ServiceImpl<KnowledgeTypeMapper, KnowledgeType> implements KnowledgeTypeService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Resource
  private KnowledgeBaseMapper knowledgeBaseMapper;

  @Override
  public List<KnowledgeTypeVO> getList(KnowledgeType knowledgeType) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    Long userId = linkappUserContextProducer.getNotNullCurrent().getId();
    // 租户id 过滤
    knowledgeType.setTenantId(tenantId);
    List<KnowledgeTypeVO> list = baseMapper.listAll(knowledgeType);
    if (!CollectionUtils.isEmpty(list)) {
      for (KnowledgeTypeVO type : list) {
        Integer count = knowledgeBaseMapper
            .countKnowledgeByTypeIdAndUserIdAndTenantId(type.getId(), userId, tenantId);
        count = (count == null) ? 0 : count;
        type.setCount(count);
      }
    }
    return list;
  }

  @Override
  public void addKnowledgeType(KnowledgeType knowledgeType) {
    knowledgeType.setCreateTime(new Date());
    knowledgeType.setCreator(linkappUserContextProducer.getCurrentUsername());
    knowledgeType.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    // 重名校验
    checkRepeatName(knowledgeType);
    baseMapper.insert(knowledgeType);
  }

  @Override
  public void updateKnowledgeType(KnowledgeType knowledgeType) {
    Long id = knowledgeType.getId();
    KnowledgeType old = baseMapper.selectById(id);
    if (null != old) {
      if (null != knowledgeType.getParentId()) {
        if (knowledgeType.getParentId().equals(id.toString())) {
          throw new BusinessException("知识类别父节点不可选择自己");
        } else {
          List<Node> list = baseMapper.findAllNodeByTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
          List<Node> currentChildrenNodeList = NodeUtil.getAllChildrenByRootId(id,list);
          Boolean flag = NodeUtil.checkChildNode(Long.parseLong(knowledgeType.getParentId()),currentChildrenNodeList);
          if(flag){
            throw new BusinessException("知识类别父节点不可选择当前节点子节点");
          }
        }
      }
      //重名校验
      knowledgeType.setTenantId(old.getTenantId());
      checkRepeatName(knowledgeType);
      knowledgeType.setModifyTime(new Date());
      knowledgeType.setModifier(linkappUserContextProducer.getCurrentUsername());
      baseMapper.updateById(knowledgeType);
    }
  }


  private void checkRepeatName(KnowledgeType knowledgeType) {
    int count = baseMapper.countNameByCondition(knowledgeType);
    if (count > 0) {
      throw new BusinessException("知识类别名称有重复");
    }
  }

  @Override
  public void deleteKnowledgeTypeById(Long id) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    KnowledgeType old = baseMapper.selectById(id);
    if (null != old) {
      // 1.校验该类别下是否存在子节点
      QueryWrapper<KnowledgeType> queryWrapper = new QueryWrapper();
      queryWrapper.eq("parent_id_", old.getId());
      queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
      List<KnowledgeType> sonList = baseMapper.selectList(queryWrapper);
      if (!CollectionUtils.isEmpty(sonList)) {
        throw new BusinessException("知识类别下存在子节点，请先删除子节点");
      }
      // 2.校验该类别下是否存在知识
      List<KnowledgeBase> list = knowledgeBaseMapper.findByTypeIdAndTenantId(id, tenantId);
      if (!CollectionUtils.isEmpty(list)) {
        throw new BusinessException("知识类别下已有知识，请先删除相关知识");
      }
      baseMapper.deleteById(id);
    }
  }
}
